<?php
/**
 * QQAS - share your knowledge to the world!
 *
 * @author		xiaochong0302 <xiaochong0302@gmail.com>
 * @copyright	Copyright (c) 2011, Koogua Studio.
 * @license		http://www.qqas.org/user_guide/license.html
 * @link		http://www.qqas.org
 * @since		Version 1.0
 * @filesource
 */


// ------------------------------------------------------------------------

/**
 * Ajax
 *
 * @category	Home
 */
class AjaxAction extends HomeAction
{
	

    //ip to country
	public function ipToCountry()
	{
	    $output = ip_to_country($_GET['ip']);
	    exit(nl2br($output));
	}


	// 获取分类
	public function getCategoryOptions()
	{
		$cateID = intval($_GET['cid']);
		$result = array();
		$categories = F('cache_categories');
		foreach ($categories as $k => $v)
		{
			if ($v['parent'] == $cateID)
			{
				$result[] = array('category_id'=>$v['category_id'], 'name'=>$v['name']);
			}
		}
		exit(json_encode($result));
	}


	//加载首页选项卡所属问题
    public function loadTabbedQuestions()
    {

        $type = $_REQUEST['type'];
        $limit = 15;

        if ('popular' == $type) //热度问题
        {
            $View = D('QuestionView');
    	    $where = array(
        		'status' => 1,
        		'is_visible' => 1,
        		'star_count' => array('gt', 0),
        	);
        	$order = array('question_id' => 'desc');
        	$questions = $View->where($where)->order($order)->limit($limit)->select();
        }
        elseif ('urgent' == $type) //紧急问题
        {
            $View = D('QuestionView');
            $where = array(
        		'status' => 1,
        		'is_visible' => 1,
        		'is_urgent' => 1,
        	);
        	$order = array('question_id' => 'desc');
        	$questions = $View->where($where)->order($order)->limit($limit)->select();
        }
        elseif ('reward' == $type) //高悬赏问题
        {
            $View = D('QuestionView');
        	$where = array(
        		'status' => 1,
        		'is_visible' => 1,
        		'is_reward' => 1,
        	);
        	$order = array('question_id' => 'desc');
        	$questions = $View->where($where)->order($order)->limit($limit)->select();
        }
        elseif ('network' == $type)
        {
            $View = D('NetworkQuestionView');
            $where = array(
                'Question.status' => 1,
                'is_visible' => 1,
                'source_user' => $this->_user['user_id'],
            );
            $order = array('question_id' => 'desc');
            $questions = $View->where($where)->order($order)->limit($limit)->select();
        }

        $this->assign('type', $type);
        $this->assign('questions', $questions);
        $html = $this->fetch();
        exit($html);
    }


    //加载相似问题(提问时的友好提示)
    public function loadSimilarQuestions()
    {
        $Question = D('Question');

        $limit = 10;
		$status = 0;
		$questions = array();
        $title = trim($_POST['title']);
		$length = strlen($title);
		$minChars = get_site_config('min_title_chars');
		$maxChars = get_site_config('max_title_chars');

		if ($length < $minChars)
		{
            $status = 1;
		}
		elseif ($length > $maxChars)
		{
		    $status = 2;
		}
		else
		{
    		$questions = $Question->getSimilarQuestions($title, $limit);
		}

		$this->assign('status', $status);
		$this->assign('questions', $questions);
		$html = $this->fetch();
		exit($html);
    }


    //加载评论
    public function loadComments()
    {
        $Comment = M('Comment');
        $View = D('CommentView');

        $limit = 50;
        $perms = array();
        $id = $_REQUEST['id'];
        $type = $_REQUEST['type'];
        $Model = ('Q' == $type) ? M('Question') : M('Answer');
        $result = $Model->find($id);

    	$isModerator = is_moderator($this->_user['user_id'], $this->_user['admin_group'], $result['category_id']);

        $perms['allow_comment'] = $this->_userGroup['allow_comment'];
		$perms['allow_edit_comment'] = $this->_userGroup['allow_edit_comment'];
		$perms['allow_delete_comment'] = $this->_userGroup['allow_delete_comment'];
		$perms['admin_edit_comment'] = $isModerator && check_moderator_perms($this->_user['admin_group'], 'allow_edit_comment');
    	$perms['admin_delete_comment'] = $isModerator && check_moderator_perms($this->_user['admin_group'], 'allow_delete_comment');

        $map = array(
            'type' => $type,
        	'is_visible' => 1,
            'related_id' => $id,
        );
        $order = array('comment_id' => 'desc');
        $comments = $View->where($map)->order($order)->limit($limit)->select();

        $this->assign('id', $id);
        $this->assign('type', $type);
        $this->assign('perms', $perms);
        $this->assign('comments', $comments);
        $html = $this->fetch();
        exit($html);
    }


    //加载用户资料卡
    public function loadUserProfile()
    {
        $userID = intval($_POST['uid']);
        $user = $this->_User->find($userID);
        $user['medals'] = array();
		$medal = explode(',', $user['medal']);
		if (!empty($medal))
		{
		    $medals = F('cache_medals');
		    foreach ($medals as $value)
	    	{
	    		if (in_array($value['medal_id'], $medal))
	    		{
	    			$user['medals'][] = $value;
	    		}
	    	}
		}
		$weekPoints = D('Activity')->userWeekPoints($userID);
		$user['week_points'] = $weekPoints;

		$this->assign('user', $user);
		$html = $this->fetch();
		exit($html);
    }
    
    
    //加载团队资料卡
    public function loadTeamProfile()
    {
    	$Team = M('Team');
        $teamID = intval($_POST['tid']);
        $team = $Team->find($teamID);
       
		$this->assign('team', $team);
		$html = $this->fetch();
		exit($html);
    }
    
    
    //加载问题修订版本
	public function loadAnswerRevision()
	{
		$AnswerRevision = M('AnswerRevision');
		$id = intval($_POST['id']);
		$revision = $AnswerRevision->find($id);
		exit(json_encode($revision));  
	}
	

	// 标签自动完成
	public function getTags()
	{
		$Model = M('Tag');
		$output = '';
		$tagName = trim($_REQUEST['q']);

		$where = array(
		    'status' => 1,
		    'name' => array('like', $tagName.'%'),
	    );
		$field = array('tag_id','name', 'question_count');
		$result = $Model->field($field)->where($where)->select();
		if ($result)
		{
			foreach($result as $value)
			{
				$output .= $value['name'] ."|". $value['question_count'] ."\n";
			}
		}
		exit($output);
	}


	// 生成验证码
	public function captcha()
	{
	    import('ORG.Util.Image');
	    $captcha = unserialize(get_site_config('captcha_parameters'));
	    switch ($captcha['char_type'])
	    {
	        case 'number':
	    	    $captcha['char_type'] = 1;
	    	    break;
	    	case 'letter':
	    		$captcha['char_type'] = 2;
	    		break;
	    	default:
	    		break;
	    }
	    Image::buildImageVerify($captcha['char_length'], $captcha['char_type'], $captcha['image_type'], $captcha['image_width'], $captcha['image_height']);
	}


	//问题评分
	public function rateAnswer()
	{
		$ansID  = intval($_POST['aid']);
		$userID = intval($this->_user['user_id']);
		$type   = trim($_POST['type']);

		$Answer = M('Answer');
		$Activity = M('Activity');

		if (!$this->_userGroup['allow_rate'])
		{
			$this->error(L(no_rate_perms));
		}
		if (exceed_activity_limit($this->_user['user_id'], $this->_user['user_group'], 'rate'))
		{
			$this->error(L('exceed_rate_limit'));
		}
		$field = array('up_rate_count','down_rate_count');
		$map = array(
			'user_id' => $userID,
			'type' => 'rate',
			'related_id' => $ansID,
		);
		$count = $Activity->where($map)->count();
		if ($count > 0)
		{
		 	$result = $Answer->field($field)->find($ansID);
		 	$result['status'] = 0;
		 	$result['info'] = L('answer_rated');
		}
		else
		{
		 	$col = ($type == 'up') ? 'up_rate_count' : 'down_rate_count';
		 	$Answer->setInc($col, 'answer_id='.$ansID, 1);
		 	$this->_User->logActivity($this->_user['user_id'], 'rate', 0, $ansID);
			$result = $Answer->field($field)->find($ansID);
		 	$result['status'] = 1;
		 	$result['info'] = '';
		 }
		 exit(json_encode($result));
	}


	//标记星号问题
	public function starQuestion()
	{
	    $Question = D('Question');
	    $Star = D('QuestionStar');

		$qstID = intval($_POST['qid']);
		$question = $Question->find($qstID);
		if (empty($question))
		{
			$this->error(L('question_not_existed'));
		}

		$allow = $this->_userGroup['allow_star_question'] && !empty($this->_user['user_id']) && ($this->_user['user_id'] != $question['poster_id']);
        if (!$allow)
        {
        	$this->error(L('no_perms_action'));
        }
        
        if (!$Star->checkStarDayLimit($this->_user['user_id'], $this->_user['user_group']))
        {
        	$this->error(L('exceed_star_limit'));
        }

		$map = array(
			'user_id' => $this->_user['user_id'],
			'question_id' => $qstID,
		);
		$count = $Star->where($map)->count();
		if ($count > 0)
		{
			$Star->where($map)->delete();
		}
		else
		{
			$data = array(
				'user_id' => $this->_user['user_id'],
				'question_id' => $qstID,
				'create_time' => time(),
			);
			$Star->add($data);
		}
		$starCount = $Question->updateStarCount($qstID);
		$result = array(
			'status' => 1,
			'info' => '',
			'star_count' => $starCount,
		);
		exit(json_encode($result));
	}


	//关注问题
    public function followQuestion()
    {
        $Question = D('Question');
        $Follow = D('QuestionFollow');

        $qstID = intval($_POST['qid']);
        $question = $Question->find($qstID);

        if (empty($question))
        {
        	$this->error(L('question_not_existed'));
        }

        $allow = $this->_userGroup['allow_follow_question'] && !empty($this->_user['user_id']) && ($this->_user['user_id'] != $question['poster_id']);
        if (!$allow)
        {
        	$this->error(L('no_perms_action'));
        }
        
        if (!$Follow->checkFollowLimit($this->_user['user_id'], $this->_user['user_group']))
        {
        	$this->error(L('exceed_question_follow_limit'));
        }

        $map = array(
            'user_id' => $this->_user['user_id'],
            'question_id' => $qstID,
        );
        $count = $Follow->where($map)->count();
        if ($count > 0)
        {
        	$this->error(L('question_follow_existed'));
        }
        else
        {
        	$where = array('question_id' => $qstID);
	        $data  = array(
	            'user_id'     => $this->_user['user_id'],
	            'question_id' => $qstID,
	            'create_time' => time(),
	        );
	    	$Follow->add($data);
	    	$Question->updateFollowCount($qstID);
	        $this->success(L('question_follow_added'));
        }
    }


    //关注用户
    public function followUser()
    {
        $Follow = D('UserFollow');

        $userID = intval($_POST['uid']);
        $user = $this->_User->find($userID);
	    if (empty($user))
        {
        	$this->error(L('user_not_existed'));
        }
        
        if (!$user['allow_follow'])
        {
        	$this->error(L('user_refuse_follow'));
        }
        
        if (!$Follow->checkFollowLimit($this->_user['user_id'], $this->_user['user_group']))
        {
        	$this->error(L('exceed_user_follow_limit'));
        }
        
        $map = array(
	        'source_user' => $this->_user['user_id'],
	        'target_user' => $userID,
	        'status' => 1,
	    );
	    $count = $Follow->where($map)->count();
        if ($count > 0)
        {
        	$this->error(L('user_following_existed'));
        }
        else 
        {
        	$Follow->addFollow($this->_user['user_id'], $userID);
			$this->success(L('user_followed'));
        }
    }


    //封锁关注
    public function blockUser()
    {
        $Follow = D('UserFollow');

        $userID = intval($_POST['uid']);
        $user = $this->_User->find($userID);
        if (empty($user))
        {
        	$this->error(L('user_not_existed'));
        }
        
        $map = array(
	        'source_user' => $this->_user['user_id'],
	        'target_user' => $userID,
	        'status' => -1,
	    );
	    $count = $Follow->where($map)->count();
        if ($count > 0)
        {
        	$this->error(L('user_blocking_existed'));
        }
        else 
        {
        	$Follow->addBlock($this->_user['user_id'], $userID);
			$this->success(L('user_blocked'));	
        }
    }
    
    
    //检查是否允许pm
    public function checkPmPerms()
    {
    	$userID = intval($_GET['uid']);
    	$user = $this->_User->find($userID);
    	if (empty($user))
    	{
    		$this->error(L('user_not_existed'));
    	}
    	$result = array(
    		'status' => $user['allow_contact'] ? 1 : 0,
    		'info' => !$user['allow_contact'] ? L('user_refuse_contact') : '',  
    	);
    	exit(json_encode($result));
    }

}
//End Class

/* End of file AjaxAction.class.php */
/* Location: ./App/Lib/Action/Home/AjaxAction.class.php */